package com.king.juc.threads;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 有返回值的线程任务
 *
 * @author king
 * @date 2020/9/2 13:55
 */
@Slf4j(topic = "c.FutureTaskDemo")
public class FutureTaskDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 原始线程任务创建
        FutureTask<Integer> t = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return 200;
            }
        });

        // lambda线程任务创建
        FutureTask<Integer> task = new FutureTask<>(() -> {
            Thread.sleep(2000);
            return 2000;
        });

        new Thread(t, "t").start();
        new Thread(task, "task").start();

        Integer result1 = null;
        Integer result2 = null;
        result1 = t.get();
        log.debug("结果是：{}", result1);

        long start = System.currentTimeMillis();
        result2 = task.get();
        log.debug("耗时{}毫秒", System.currentTimeMillis() - start);

    }
}
